package tech.aistar.day11;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 本类用来演示: Lock可以用来判断是否获取到锁
 *
 * @author: success
 * @date: 2022/8/2 1:31 下午
 */
public class LockTryLockDemo {
    public static void main(String[] args) {
        //Lock可以判断出来是否获取锁资源
        Lock lock = new ReentrantLock();
        Thread t1 = new Thread(()->{
            System.out.println("t1...启动!");
            //尝试获取锁,等待1s还没有获取到锁,直接返回
            try {
                if(!lock.tryLock(5, TimeUnit.SECONDS)){
                    System.out.println("等待1s后,获取锁失败!");
                    return;
                }
                System.out.println("t1获得了锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                //释放锁
                lock.unlock();

            }
        });

        //main线程
        try {
            lock.lock(); // lock锁在main线程的手上

            System.out.println("main线程获取到了锁!");

            t1.start();
            //让t1启动起来...
            while(true){
                //业务...
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }
}
